package com.jboost.common.util.qiniu;

import com.jboost.common.file.constant.VideoBitrateEnum;
import com.jboost.common.util.UploadCategoryEnum;
import com.jboost.common.util.oConvertUtils;
import com.jboost.config.FileConfig;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.StringUtils;
import com.qiniu.util.UrlSafeBase64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Component
@ConditionalOnProperty(prefix = "qiniu", value = "AK", matchIfMissing = true)
@ConfigurationProperties(prefix = "qiniu")
public class QiniuUtil {
    public static String SCREENSHOT_SUFFIX = "-screenshot.jpg";
    private static String ak;
    private static String sk;
    private static String bucket;
    private static String bucketDomain;

    private static QiniuUtil util;

    public static String getBucket() {
        return bucket;
    }

    @Value("${qiniu.AK}")
    public void setAk(String ak) {
        QiniuUtil.ak = ak;
    }
    @Value("${qiniu.SK}")
    public void setSk(String sk) {
        QiniuUtil.sk = sk;
    }
    @Value("${qiniu.bucket}")
    public void setBucket(String bucket) {
        QiniuUtil.bucket = bucket;
    }
    @Value("${qiniu.bucketDomain}")
    public void setBucketsDomain(String bucketsDomain) {
        QiniuUtil.bucketDomain = bucketsDomain;
    }


    public static String getFullUrl(String fileName, String bucket) {
        if (fileName.indexOf("/") == 0) {
            fileName = fileName.substring(1);
        }
        String newBucket;
        if (oConvertUtils.isNotEmpty(bucket)) {
            newBucket = bucket;
        }else {
            newBucket = QiniuUtil.bucket;
        }
//        String fileName = "公司/存储/qiniu.jpg";
        String domainOfBucket = QiniuUtil.bucketDomain;
        if(domainOfBucket.indexOf("http")<0){
            domainOfBucket = "http://"+domainOfBucket;
        }
        String encodedFileName = null;
        try {
            encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
            if (encodedFileName.indexOf(".m3u8")>0){
                encodedFileName +="?pm3u8/0";
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);
        Auth auth = Auth.create(ak, sk);
        long expireInSeconds = 1800;//半小时，可以自定义链接过期时间
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        return finalUrl;
    }


    public static QiniuUtil getInstance(){
        if(null== QiniuUtil.util){
            QiniuUtil.util = new QiniuUtil();
        }
        return QiniuUtil.util;
    }


    /**
     * 获取上传的Token
     */
    public QiniuUploadTokenVo createUploadToken(UploadCategoryEnum category, String fileName){
        QiniuUploadTokenVo vo = new QiniuUploadTokenVo();
        Auth auth = Auth.create(ak, sk);
        StringMap putPolicy = new StringMap();
        List<String> bitrateList = new ArrayList<String>();
        String notifyUrl = (FileConfig.PORT == null || "80".equals(FileConfig.PORT)?"http://":"https://") + FileConfig.WEB_HOST + (FileConfig.PORT == null ? "" : (":" + FileConfig.PORT)) + FileConfig.CONTEXT + "/open/qiniu/taskCallBack";
        if (category == UploadCategoryEnum.VIDEO){
            //生成文件名
            UUID randomUUID = UUID.randomUUID();
            if (StringUtils.isNullOrEmpty(fileName)){
                fileName = randomUUID.toString();
            }
            //视频转成m3u8-720k
            String fileName720p = bucket+":"+fileName+"-"+ VideoBitrateEnum.B_720P.code()+".m3u8";
            String fileName1080p = bucket+":"+fileName+"-"+ VideoBitrateEnum.B_1080P.code()+".m3u8";
            String fileName2000p = bucket+":"+fileName+"-"+ VideoBitrateEnum.B_2K.code()+".m3u8";
            String screenshotName = bucket+":"+fileName+QiniuUtil.SCREENSHOT_SUFFIX;
            String screenshot = "vframe/jpg/offset/0/h/400|saveas/"+UrlSafeBase64.encodeToString(screenshotName);
            String toM3u8_720p = "avthumb/m3u8/ab/128k/ar/22050/acodec/libfaac/vb/800k/s/1280x720/autoscale/1/r/20/vcodec/libx264/stripmeta/0|saveas/"+UrlSafeBase64.encodeToString(fileName720p);
            String toM3u8_1080p = "avthumb/m3u8/ab/192k/ar/44100/acodec/libfaac/vb/1.2m/s/1920x1080/autoscale/1/r/30/vcodec/libx264/stripmeta/0|saveas/"+UrlSafeBase64.encodeToString(fileName1080p);
            String toM3u8_2000p = "avthumb/m3u8/ab/320k/ar/96000/acodec/libfaac/vb/1.8m/s/2560x1440/autoscale/1/hr/1/r/60/vcodec/libx264/stripmeta/0|saveas/"+UrlSafeBase64.encodeToString(fileName2000p);
//            String avthumbMp4Fop = String.format("avthumb/mp4|saveas/%s", UrlSafeBase64.encodeToString(saveMp4Entry));
//            String vframeJpgFop = String.format("vframe/jpg/offset/1|saveas/%s", UrlSafeBase64.encodeToString(saveJpgEntry));
            //将多个数据处理指令拼接起来
            String persistentOpfs = StringUtils.join(new String[]{ screenshot,toM3u8_720p, toM3u8_1080p,toM3u8_2000p }, ";");

            putPolicy.put("persistentOps", persistentOpfs);
            putPolicy.put("persistentNotifyUrl", notifyUrl);
            bitrateList.add(VideoBitrateEnum.B_720P.code());
            bitrateList.add(VideoBitrateEnum.B_1080P.code());
            bitrateList.add(VideoBitrateEnum.B_2K.code());
        }else if (category == UploadCategoryEnum.APP_VIDEO){
            //生成文件名
            UUID randomUUID = UUID.randomUUID();
            if (StringUtils.isNullOrEmpty(fileName)){
                fileName = randomUUID.toString();
            }
            String fileName720p = bucket+":"+fileName+"-"+ VideoBitrateEnum.B_720P.code()+".m3u8";
            String screenshotName = bucket+":"+fileName+QiniuUtil.SCREENSHOT_SUFFIX;
            String screenshot = "vframe/jpg/offset/0/h/400|saveas/"+UrlSafeBase64.encodeToString(screenshotName);
//            String toM3u8_720p = "avthumb/m3u8/ab/128k/ar/22050/acodec/libfaac/vb/800k/s/1280x720/r/20/vcodec/libx264/stripmeta/0|saveas/"+UrlSafeBase64.encodeToString(fileName720p);
            String toM3u8_720p = "avthumb/m3u8/ab/128k/ar/22050/acodec/libfaac/vb/800k/r/20/vcodec/libx264/stripmeta/0|saveas/"+UrlSafeBase64.encodeToString(fileName720p);

            String persistentOpfs = StringUtils.join(new String[]{ screenshot,toM3u8_720p }, ";");
            putPolicy.put("persistentOps", persistentOpfs);
            putPolicy.put("persistentNotifyUrl", notifyUrl);
            bitrateList.add(VideoBitrateEnum.B_720P.code());
        }
        System.out.println("***********"+putPolicy.get("persistentOps"));
        System.out.println("***********"+putPolicy.get("persistentNotifyUrl"));
//        if(StringUtils.isNullOrEmpty(fileName)){
//            return auth.uploadToken(bucket, null, 7200L, putPolicy, true);
//        }
        vo.setBitrateList(bitrateList);
        vo.setFileKey(fileName);
        vo.setToken(auth.uploadToken(bucket, fileName, 3600L, putPolicy, true));

        return vo;
    }

}
